{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# read data form csv\n",
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "## remove duplicate rows\n",
    "def unique(a): \n",
    "    order = np.lexsort(a.T)\n",
    "    a = a[order]\n",
    "    diff = np.diff(a, axis=0)\n",
    "    ui = np.ones(len(a), 'bool')\n",
    "    ui[1:] = (diff != 0).any(axis=1) \n",
    "    return a[ui]\n",
    "## read the the file saving premise\n",
    "def getpremise(wheel_type, batnum): \n",
    "#     name_folder = \"S:/Polyspace/R2020a/bin/work/grdsim_cluster\"\n",
    "    name_folder = \"C:/Users/Anthony Dave/Desktop/Undergraduate thesis/数据\"\n",
    "    names = 'w' + str(wheel_type) + 'batch_' + str(batnum) + '_premise.csv'\n",
    "    filename_premise = os.path.join(name_folder, names)\n",
    "    nppremise = np.loadtxt(open(filename_premise, \"rb\"), delimiter=\",\")\n",
    "    nppremise = unique(nppremise)\n",
    "    if wheel_type == 1:\n",
    "        dfpremise = pd.DataFrame(data=nppremise, columns=[\"grits_num\",\"shape\",\"trim_h\",\"omega\",\"h2w_ratio\",\n",
    "                                                        \"Rarea\",\"sigmah\",\"sigmasw\",\"fillet_mode\",\"Ra\",\"Cr\"])\n",
    "    elif wheel_type == 2:\n",
    "        dfpremise = pd.DataFrame(data=nppremise, columns=[\"grits_num\",\"theta\",\"SepGap\",\"RowGap\",\"k_dev\",\"shape\",\"trim_h\",\n",
    "                                                          \"omega\",\"h2w_ratio\",\"Rarea\",\"sigmah\",\"sigmasw\",\"fillet_mode\"\n",
    "                                                          ,\"Ra\",\"Cr\"])\n",
    "    return nppremise, dfpremise"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "## read conclusion data from csv\n",
    "def getdata(wheel_type, nppremise, data_type):\n",
    "    data_folder = \"C:/Users/Anthony Dave/Desktop/Undergraduate thesis/数据/1105effectofshape\"\n",
    "    dataname = 'N'\n",
    "    dataname += str(np.int(nppremise[0]))\n",
    "    posi = 0\n",
    "    if wheel_type == 2:\n",
    "        posi = 4\n",
    "        dataname += ('tgw' + str(np.int(nppremise[1])) +\n",
    "                              'kd' + str(np.int(nppremise[4])) +\n",
    "                              'Sgap' + (str(nppremise[2])  if nppremise[2] != 0 else str(np.int(nppremise[2]))) +\n",
    "                              'Rgap' + str(np.int(nppremise[3])))\n",
    "    dataname +=  ('w' + str(np.int(nppremise[3+posi])) + \n",
    "                  'Rarea' + (str(nppremise[5+posi]) if nppremise[5+posi] != 0 else str(np.int(nppremise[5+posi])))+\n",
    "                  'hsg' + (str(nppremise[6+posi]) if nppremise[6+posi] != 0 else str(np.int(nppremise[6+posi])))+\n",
    "                  'swsg' + (str(nppremise[7+posi]) if nppremise[7+posi] != 0 else str(np.int(nppremise[6+posi])))+\n",
    "                  data_type + '.csv')\n",
    "    filename_force = os.path.join(data_folder,dataname)\n",
    "    npdata = np.loadtxt(open(filename_force, \"rb\"), delimiter=\",\")\n",
    "    if data_type == '-GForce':\n",
    "        dfdata = pd.DataFrame(data=npdata, columns=[\"time\", \"Fn\", \"Ft\"])\n",
    "    return npdata, dfdata"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.ticker import MaxNLocator\n",
    "from matplotlib import cm\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "\n",
    "def plotsave(xname,yname,zname,wheel_type,batum):\n",
    "    data_folder = r\"1105\"\n",
    "    output_filename = 'w' + str(wheel_type) + 'batch' + str(batnum) + xname + '&' + yname + '-' + zname\n",
    "    fullpath = os.path.join(data_folder, output_filename + \".jpg\")\n",
    "    \n",
    "    x = Xt[xname].values\n",
    "    y = Xt[yname].values\n",
    "    z = Xt[zname].values\n",
    "    \n",
    "    fig = plt.figure(figsize=(10,10))\n",
    "    ax = fig.gca(projection='3d')\n",
    "    surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0)\n",
    "\n",
    "    plt.colorbar(surf,fraction=0.040, pad=0.04)\n",
    "    fig.tight_layout()\n",
    "\n",
    "    ax.view_init(elev=20., azim=40)\n",
    "    ax.set_xlabel(xname)\n",
    "    ax.set_ylabel(yname)\n",
    "    ax.set_zlabel(zname)\n",
    "    \n",
    "    # plt.show()\n",
    "    fig.savefig(fullpath)\n",
    "    # ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['omega', 'Rarea', 'Ra', 'Cr', 'Fn', 'Ft', 'Ra_abvoe_mean'], dtype='object')\n"
     ]
    }
   ],
   "source": [
    "# choose the premise dataset\n",
    "wheel_type = 1\n",
    "batnum = 1\n",
    "nppremise, dfpremise = getpremise(wheel_type,batnum)\n",
    "dfpremise.head()\n",
    "\n",
    "data_type = '-GForce'\n",
    "# data_type = '' # you should set the columns' names first\n",
    "npforce = []\n",
    "dfforce = []\n",
    "for i in range(0,len(nppremise)):\n",
    "    npfort, dffort = getdata(wheel_type, nppremise[i,:], data_type)\n",
    "    npforce.append(npfort)\n",
    "    dfforce.append(dffort)\n",
    "    \n",
    "# temporarily define\n",
    "threshold_down = 1.5*pow(10,-4)\n",
    "threshold_up = 3.5*pow(10,-4)\n",
    "grinding_forcen = []\n",
    "grinding_forcet = []\n",
    "for i in range(0,len(npforce)):\n",
    "    grinding_range = np.where(np.logical_and(npforce[i][:,0]>=threshold_down, npforce[i][:,0]<=threshold_up))\n",
    "    siz = len(grinding_range)\n",
    "    minnum = np.amin(grinding_range)\n",
    "    maxnum = np.amax(grinding_range)\n",
    "    grinding_forcen = np.append(grinding_forcen,(np.sum(npforce[i][minnum:maxnum,1])/siz))\n",
    "    grinding_forcet = np.append(grinding_forcet,(np.sum(npforce[i][minnum:maxnum,2])/siz))\n",
    "\n",
    "# data mining variance threshold\n",
    "from sklearn.feature_selection import VarianceThreshold\n",
    "def variance_threshold_selector(data):\n",
    "    selector = VarianceThreshold()\n",
    "    selector.fit(data)\n",
    "    return data[data.columns[selector.get_support(indices=True)]]\n",
    "Xt = variance_threshold_selector(dfpremise)\n",
    "Xt = pd.DataFrame(Xt)\n",
    "Xt[\"Fn\"] = pd.DataFrame(data=np.transpose([grinding_forcen]), columns=[\"Fn\"])\n",
    "Xt[\"Ft\"] = pd.DataFrame(data=np.transpose([grinding_forcet]), columns=[\"Ft\"])\n",
    "Xt[\"Ra_abvoe_mean\"] = Xt['Ra'] > Xt['Ra'].mean()\n",
    "\n",
    "# print(Xt.columns)\n",
    "plotsave('omega','Rarea','Ra',wheel_type, batnum)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "# for wheel_type in range(1,2):\n",
    "#     print(wheel_type)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
